import {Form, Switch, Input, Button, InputNumber, TimePicker, message} from "antd";
import React, {Component} from "react";
import GoBack from "@/components/TheGoBack";
import TheUpload from '@/components/TheUpload';
import moment from 'moment';
import {apiAddDoctor, apiViewDoctor, apiEditDoctor} from "@/request/doctor"
import { phoneReg } from '@/utils/regexp';

export default class AddDoctor extends Component {
    constructor() {
        super()
        this.formRef = React.createRef()
        this.state = {
            fileList: [],
            title: '',
            defaultList: [
                {checked: false, time: ["08:30","21:00"]},
                {checked: false, time: ["08:30","21:00"]},
                {checked: false, time: ["08:30","21:00"]},
                {checked: false, time: ["08:30","21:00"]},
                {checked: false, time: ["08:30","21:00"]},
                {checked: false, time: ["08:30","21:00"]},
                {checked: false, time: ["08:30","21:00"]},
            ]
        }
    }

    async componentDidMount() {
        console.log(this.props);
        if (this.props.location.pathname === '/doctor/list/add') {
            this.setState({
                title: '创建医生',
            })
            console.log(this.state.title);
        } else {
            this.setState({
                title: '修改医生',
            })
            let res = await apiViewDoctor(this.props.match.params.id)
            if (res.code === 0) {
                console.log(res.data.doctorHeadPortrait);
                this.setState({
                    // 图片回显
                    fileList: [
                        {
                            name: 'image',
                            uid: -1,
                            url: res.data.doctorHeadPortrait,
                            status: 'done'
                        }
                    ]
                })
                let {defaultList} = this.state
                res.data.doctorScheduleList.forEach(item=>{
                    defaultList[item.week-1].checked = true
                    defaultList[item.week-1].time = [item.beginTime,item.endTime]
                })
                this.formRef.setFieldsValue(
                    {
                        doctorName: res.data.doctorName,
                        doctorMobile: res.data.doctorMobile,
                        doctorPrice: res.data.doctorPrice / 100,
                        doctorTag: res.data.doctorTag,
                        doctorTitle: res.data.doctorTitle,
                        doctorHeadPortrait: res.data.doctorHeadPortrait,
                        list: defaultList
                    }
                );
            }
        }
    }

    // 医生头像上传
    getFileResult = (value) => {
        if (value.length) {
            let str = value.map(v => {
                if (v.response && v.response.code === 0) {
                    return v.response.data
                }
            }).join(',')
            this.formRef.setFieldsValue({doctorHeadPortrait: str});
        } else {
            this.formRef.setFieldsValue({doctorHeadPortrait: ''});
        }
    };
    // 保存配置
    onFinish = async (values) => {
        console.log(values)
        let doctorScheduleList = [],flag = false
        values.list.forEach((item,index)=>{
            if (item.checked){
                if (item.time[0]===item.time[1]){
                    flag = true
                }
                doctorScheduleList.push({
                    week: index+1,
                    beginTime: item.time[0],
                    endTime: item.time[1],
                })
            }
        })
        delete values.list
        if (flag){
            message.error("出诊班次:结束时间应大于开始时间")
            return
        }
        values.doctorScheduleList = doctorScheduleList
        // return
        values.doctorPrice = values.doctorPrice * 100
        if (this.state.title === '创建医生') {
            let res = await apiAddDoctor({...values})
            if (res.code === 0) {
                React.$message({
                    type: 'info',
                    content: '新增成功'
                })
                this.props.history.goBack(-1)
            }
        } else {
            let res = await apiEditDoctor({doctorId: this.props.match.params.id, ...values})
            if (res.code === 0) {
                React.$message({
                    type: 'info',
                    content: '修改成功'
                })
                this.props.history.goBack()
            }
        }

    }
    //
    range = (start, end) => {
        const result = [];
        for (let i = start; i <= end; i++) {
            result.push(i);
        }
        return result;
    };
    disabledTime = (now, type) => {
        if (type === 'start') {
            return {
                disabledHours: (e) => {
                    return this.range(0, 7)
                },
                disabledMinutes: (e) => {
                    if (e === 8) {
                        return this.range(0, 29)
                    }
                }
            };
        } else {
            return {
                disabledHours: (e) => {
                    return this.range(22, 23)
                },
                disabledMinutes: (e) => {
                    if (e === 21) {
                        return this.range(30, 59)
                    }
                }
            };
        }
    }

    render() {
        const {title, fileList, defaultList} = this.state
        return (
            <>
                <div className="p-layout-box">
                    <GoBack history={this.props.history} style={{margin: 20}} title={title}/>
                    <div style={{height: '100%', overflowY: 'auto', padding: 20}}>
                        <Form
                            ref={ref => this.formRef = ref}
                            onFinish={this.onFinish}
                            initialValues={{
                                list: defaultList
                            }}
                        >
                            <Form.Item label="医生名称" name='doctorName'
                                       rules={[
                                           {
                                               required: true,
                                               message: '请输入医生名称',
                                           },
                                       ]}>
                                <Input maxLength={5} placeholder="请输入医生名称" style={{width: 300}}/>
                            </Form.Item>
                            <Form.Item label="医生头像" name='doctorHeadPortrait'
                                       rules={[
                                           {
                                               required: true,
                                               message: '请选择医生头像',
                                           },
                                       ]}>
                                <TheUpload getFileResult={this.getFileResult} len={1} fileList={fileList}/>
                                <div style={{fontSize: 12}}>支持jpg .jpeg .bmp .png格式,大小不超过10M</div>
                                <div style={{fontSize: 12, marginTop: 5}}>最多上传1张,建议尺寸:750px * 448px</div>
                            </Form.Item>
                            <Form.Item label="医生职称" name='doctorTitle'
                                       rules={[
                                           {
                                               required: true,
                                               message: '请输入医生职称',
                                           },
                                       ]}>
                                <Input maxLength={8} placeholder="最多允许输入8个字" style={{width: 300}}/>
                            </Form.Item>
                            <Form.Item label="医生电话" name='doctorMobile'
                                       rules={[
                                           {
                                               required: true,
                                               message: '请输入医生电话',
                                           },
                                           {
                                               message: '请输入正确的电话号码！',
                                               pattern: phoneReg
                                           }
                                       ]}>
                                <Input maxLength={11} placeholder="请输入医生电话" style={{width: 300}}/>
                            </Form.Item>
                            <Form.Item label="展示标签" name='doctorTag'
                                       rules={[
                                           {
                                               required: true,
                                               message: '请输入展示标签',
                                           },
                                       ]}>
                                <Input maxLength={6} placeholder="最多输入6个字" style={{width: 300}}/>
                            </Form.Item>
                            <Form.Item label="挂号价格" name='doctorPrice'
                                       rules={[
                                           {
                                               required: true,
                                               message: '请输入挂号价格',
                                           },
                                       ]}>
                                <InputNumber prefix="￥" min={0.01} precision={2} placeholder="请输入挂号价格" style={{width: 300}}/>
                            </Form.Item>
                            <Form.List
                                name="list"
                            >
                                {(fields, {add, remove}, {errors}) => (
                                    <Form.Item label="出诊班次" required={true}>
                                        {fields.map((field, index) => (
                                            <div style={{display: "flex"}}>
                                                <Form.Item>
                                                    {field.key === 0 &&
                                                        <span className="ant-form-text">周一</span>}
                                                    {field.key === 1 &&
                                                        <span className="ant-form-text">周二</span>}
                                                    {field.key === 2 &&
                                                        <span className="ant-form-text">周三</span>}
                                                    {field.key === 3 &&
                                                        <span className="ant-form-text">周四</span>}
                                                    {field.key === 4 &&
                                                        <span className="ant-form-text">周五</span>}
                                                    {field.key === 5 &&
                                                        <span className="ant-form-text">周六</span>}
                                                    {field.key === 6 &&
                                                        <span className="ant-form-text">周日</span>}
                                                </Form.Item>
                                                <Form.Item
                                                    name={[field.name, 'checked']}
                                                    // key={field.key}
                                                    style={{marginRight: 20}}
                                                    valuePropName={'checked'}
                                                >
                                                    <Switch/>
                                                </Form.Item>
                                                <Form.Item noStyle shouldUpdate>
                                                    {({getFieldValue}) =>
                                                        getFieldValue(['list', field.name, 'checked']) ?
                                                            <Form.Item
                                                                name={[field.name, 'time']}
                                                                rules={[
                                                                    {
                                                                        required: true,
                                                                        message: '请选择时间'
                                                                    },
                                                                ]}
                                                                // key={field.key}
                                                                getValueProps={v => ({
                                                                    value: v ? [moment(v[0], 'HH:mm'), moment(v[1], 'HH:mm')] : null,
                                                                    v
                                                                })}
                                                                getValueFromEvent={e => e ? [moment(e[0]).format('HH:mm'), moment(e[1]).format('HH:mm')] : e}
                                                            >
                                                                <TimePicker.RangePicker
                                                                    format="HH:mm"
                                                                    minuteStep={30}
                                                                    // disabledTime={this.disabledTime}
                                                                />
                                                            </Form.Item> : null
                                                    }
                                                </Form.Item>
                                            </div>
                                        ))}
                                    </Form.Item>
                                )}
                            </Form.List>
                            <Form.Item
                                style={{marginTop: 40,}}
                                wrapperCol={{
                                    offset: 2,
                                    span: 16,
                                }}>
                                <Button style={{width: 200}} type="primary" htmlType="submit" onClick={this.add}>
                                    保存配置
                                </Button>
                            </Form.Item>
                        </Form>
                    </div>
                </div>
            </>
        )
    }
}
